package com.zz.study.sharding.algorithm;

import cn.hutool.core.date.DateUtil;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.Objects;

/**
 * created by xjx on  2023-12-28 17:33
 */
public class PreciseAlgorithmTrackData implements PreciseShardingAlgorithm<Timestamp> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Timestamp> preciseShardingValue) {
        for (String str : collection) {
            // 此处输出的是物理表名
            int index = str.lastIndexOf("_");
            String logicalYear = str.substring(index+1,index+5);
            String logicalMonth = str.substring(index+5,str.length());
            String dateTimeStr ="";
            //String dateTimeStr = DateUtil.format(new Date(((Timestamp)preciseShardingValue.getValue()).getTime()),"yyyy-MM-dd");
           Object dateTime = preciseShardingValue.getValue();
           if(!Objects.isNull(dateTime)){
               if(dateTime instanceof Timestamp){
                   dateTimeStr = DateUtil.format(new Date(((Timestamp)preciseShardingValue.getValue()).getTime()),"yyyy-MM-dd");
               }else if(dateTime instanceof String){
                   dateTimeStr = (String)dateTime;
               }
           }
            dateTimeStr=dateTimeStr.substring(0,7).replace("-","");
            String dateTimeStrYear = dateTimeStr.substring(0,4);
            String dateTimeMongth = dateTimeStr.substring(4,6);
            dateTimeMongth=new Integer(Integer.parseInt(dateTimeMongth)).toString();
            if(logicalYear.equals(dateTimeStrYear) && logicalMonth.equals(dateTimeMongth)){
                return str;
            }
        }
        return null;
    }
}
